package com.hzw.saas.web.app.user.controller;

import javax.validation.constraints.Pattern;

import com.hzw.saas.api.property.enmus.SysDictKeyEnum;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.util.AccountValidatorUtil;
import com.hzw.saas.common.verify.aspect.PuzzleVerify;
import com.hzw.saas.common.verify.service.IVerifyService;
import com.hzw.saas.web.app.aspect.RedisPeriodLock;
import com.hzw.saas.web.app.user.param.EmailVerifyParam;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;

/**
 * 邮箱验证
 *
 * @author zzl
 * @since 01/13/2021
 */
@Controller
@AllArgsConstructor
@Validated
@Api(tags = "用户中心/邮箱验证")
public class EmailController {

    private final static String VERIFY_LOCK_TIME_KEY = "verifyLockTime";

    IVerifyService verifyService;

    @ApiOperationSort(1)
    @SysLog(operation = "获取邮箱验证码", mode = 3)
    @GetMapping("/user/verify/email/{email}")
    @ApiOperation(value = "获取邮箱验证码", notes = "给指定的邮箱发送验证信息")
    @PuzzleVerify(captchaVerification = "#token", pointJson = "#pointJson")
    @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String")
    @ApiResponses({@ApiResponse(code = 200, message = "发送邮箱验证码成功"), @ApiResponse(code = 400, message = "发送邮箱验证码失败")})
    @RedisPeriodLock(lockName = "verifyEmail", key = "#email", expireKeyEnum = SysDictKeyEnum.VERIFY_LOCK_TIME, lockMsg = "请勿频繁获取验证码")
    public ResponseEntity<String> sendEmail(@PathVariable @Pattern(regexp = AccountValidatorUtil.REGEX_EMAIL, message = "邮箱格式不正确") String email,
                                            @ApiParam(value = "verifyToken，二次校验参数(token)", required = true) @RequestParam(required = false) String token,
                                            @ApiParam(value = "pointJson，{\"x\":0,\"y\":0}", required = true) @RequestParam(required = false) String pointJson) {
        if (verifyService.sendEmailVerifyCode(email)) {
            return ResponseEntity.ok("发送邮箱验证码成功");
        }
        return ResponseEntity.badRequest().body("发送邮箱验证码失败");
    }

    @PutMapping("/user/verify/email")
    @SysLog(operation = "验证邮箱验证码", mode = 3)
    @ApiOperation(value = "验证邮箱验证码", notes = "校验用户输入的邮箱验证码")
    @ApiResponses({
        @ApiResponse(code = 200, message = "验证成功"),
        @ApiResponse(code = 400, message = "验证失败")
    })
    @ApiOperationSort(2)
    public ResponseEntity<String> verifySms(@Validated @RequestBody EmailVerifyParam param) {
        boolean verify = verifyService.verify(param.getEmail(), param.getVerifyCode(), false);
        if (!verify) {
            return ResponseEntity.badRequest().body("短信邮箱验证失败");
        }
        return ResponseEntity.ok("邮箱验证成功");
    }

}
